package edu.nf.ch01.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author wangl
 * @date 2025/4/22
 */
public class MybatisUtils {

    /**
     * 声明SqlSessionFactory，用于创建SqlSession
     */
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 类加载时在静态代码块完成初始化
     */
    static {
        try {
            //读取mybatis.xml文件并返回一个输入流
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            //通过SqlSessionFactoryBuilder类来解析流的数据并初始化
            //SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建SqlSession对象
     * @return
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}